<?php
declare (strict_types = 1);

namespace app\index\controller;
use app\BaseController;
use app\common\model\Menu as MenuModel;
use app\common\model\User as UserModel;
use think\Facade\Session;
use think\facade\Validate;
use think\Facade\View;
use think\helper\Str;
use think\validate\ValidateRule as Rule;

class Index extends BaseController {
	/**
	 * 首页
	 * @DateTime 2019-12-21
	 * @Author   BadmintonCode
	 */
	public function index() {
		//$menus = \app\common\model\Menu::getMenus();
		$menu_ids = $this->request->group->rules;
		$menulist = MenuModel::whereAvailable(1)
			->order('displayorder', 'asc')
			->column('*', 'menu_id');
		foreach ($menulist as $key => $value) {
			if (!$menulist[$key]['url']) {
				$menulist[$key]['path'] = url('/' . $menulist[$key]['app'] . '/' . $menulist[$key]['controller'] . '/' . $menulist[$key]['action']);
			} else {
				$menulist[$key]['path'] = $menulist[$key]['url'];
			}

			if ($value['parent_id'] != 0) {
				$menulist[$value['parent_id']]['son'][] = $value['menu_id'];
			}
		}
		if (!in_array(-1, $menu_ids)) {
			//自顶向下
			foreach ($menulist as $key => $value) {
				if (in_array($menulist[$key]['menu_id'], $menu_ids)) {
					$menulist[$key]['show'] = true;
					if ($menulist[$key]['son']) {
						foreach ($menulist[$key]['son'] as $v1) {
							$menulist[$v1]['show'] = true;
							if ($menulist[$v1]['son']) {
								foreach ($menulist[$v1]['son'] as $v2) {
									$menulist[$v2]['show'] = true;
								}
							}
						}
					}
				}
			}
			foreach ($menulist as $key => $value) {
				if (in_array($menulist[$key]['menu_id'], $menu_ids)) {
					$menulist[$key]['show'] = true;
					if ($menulist[$key]['parent_id']) {
						$menulist[$menulist[$key]['parent_id']]['show'] = true;
						if ($menulist[$menulist[$key]['parent_id']]['parent_id']) {
							$menulist[$menulist[$menulist[$key]['parent_id']]['parent_id']]['show'] = true;
						}
					}
				}
			}
		}
		$menus = [];
		foreach ($menulist as $key => $value) {
			if (!($value['show'] || in_array(-1, $menu_ids)) || $value['level'] != 1) {
				continue;
			}

			if ($value['son']) {
				foreach ($value['son'] as $v) {
					if ($menulist[$v]['show'] || in_array(-1, $menu_ids)) {
						$item = $menulist[$v];
						if ($item['son']) {
							foreach ($item['son'] as $v1) {
								if ($menulist[$v1]['show'] || in_array(-1, $menu_ids)) {
									$item['children'][] = $menulist[$v1];
								}
							}
						}
						$value['children'][] = $item;
					}
				}
			}
			$menus[] = $value;
		}
		//$menus = getMenu();

		//dump($menus);
		View::assign('menus', $menus);
		View::assign('user', $this->user);
		return View::fetch();
	}

	/**
	 * 登录后欢迎界面
	 * @DateTime 2019-12-13
	 * @Author   BadmintonCode
	 */
	public function welcome() {
		return $this->settings['welcometips'];
	}
	/**
	 * 登录
	 * @DateTime 2019-12-13
	 * @Author   BadmintonCode
	 */
	public function login() {
		if ($this->user && !\think\Facade\Env::has('AUTO_LOGIN')) {
			return success('您已登录成功', url('/'));
		}
		if ($this->request->isAjax()) {
			$token = $this->request->checkToken('__token__', $this->request->post());
			if ($token !== true) {
				return doReturn('token', ['tokencheck' => $token], true);
			}
			$username = $this->request->post('username', '', 'trim,strip_tags');
			if (!$username) {
				return doReturn('user.username', true);
			}
			$password = $this->request->post('password', '', 'trim,strip_tags');
			if (!$password) {
				return doReturn('password.empty', true);
			}
			$user = UserModel::where('email|user_id', $username)->find();
			if (!$user) {
				trace('登录' . $username . '不存在', 'notice');
				return doReturn('user.notExist', true);
			}
			if (salt_password($user->salt, $password) != $user->password) {
				trace('登录' . $username . '密码错误', 'notice');
				return doReturn('user.error', true);
			}
			if ($user->status == 0) {
				trace($username . '无权登录', 'notice');
				return doReturn('user.baned', true);
			}
			$user->last_ip = $user->login_ip;
			$user->last_time = $user->getData('login_time');
			$user->login_time = time();
			$user->login_ip = request()->ip();

			$user->save();
			Session::set('user', $user);
			return doSuccess('user.success', ['url' => '/']);
		}
		$this->noJs();
		$this->title('登录');
		return View::fetch();
	}
	/**
	 * 退出登录
	 * @DateTime 2019-12-20
	 * @Author   BadmintonCode
	 */
	public function logout() {
		//Session::set();
		Session::clear();
		return success('退出成功，即将跳转回首页', url('/'));
	}
	/**
	 * 修改资料项
	 * @DateTime 2019-12-21
	 * @Author   BadmintonCode
	 */
	public function info() {
		if ($this->request->isAjax() && $this->request->isPost()) {
			$pagemod = $this->request->post('pagemod'); //模块id
			$fields = \app\common\model\Field::whereFindInSet('mods', $pagemod)->order('displayorder', 'asc')->where('available', 1)->select()->toArray();
			$data = [];
			$rules = [];
			$arrayField = [];
			foreach ($fields as $item) {
				$rule = [];
				if (in_array($item['type'], ['text', 'textarea', 'password', 'date'])) {
					if ($item['required']) {
						$rule[] = 'require';
					}
					$data['field' . $item['field_id']] = $this->request->post('field' . $item['field_id'], '', 'addslashes');
				} elseif (in_array($item['type'], ['number', 'switch'])) {
					$data['field' . $item['field_id']] = $this->request->post('field' . $item['field_id']);
					if (strlen((string) $data['field' . $item['field_id']]) > 0 || $item['type'] == 'switch') {
						$data['field' . $item['field_id']] = intval($data['field' . $item['field_id']]);
					}

					if ($item['type'] == 'switch') {
						//开关校验01
						$rule[] = 'in:0,1';
					} else {
						$rule[] = 'integer';
						if ($item['required']) {
							$rule[] = 'require';
						}
					}
				} elseif (in_array($item['type'], ['radio', 'select'])) {
					$data['field' . $item['field_id']] = $this->request->post('field' . $item['field_id'], '', 'addslashes,trim,strip_tags');
					if ($item['required']) {
						$rule[] = 'require';
						$setting = array_map(function ($n) {
							return explode('|', $n)[0];
						}, explode(',', $item['setting']));
						$rule[] = 'in:' . implode(',', $setting);
					}
				} elseif (in_array($item['type'], ['checkbox'])) {
					$data['field' . $item['field_id']] = $this->request->post('field' . $item['field_id']);
					$setting = array_map(function ($n) {
						return explode('|', $n)[0];
					}, explode(',', $item['setting']));
					$rule = function ($value) use ($setting, $item) {
						foreach ($value as $v) {
							if (!in_array($v, $setting)) {
								return $item['title'] . '选择不正确';
							}

						}
						return false;
					};
					$arrayField[] = 'field' . $item['field_id'];
				}
				if ($rule) {
					if (is_array($rule)) {
						$rule = implode('|', $rule);
					}
					$rules['field' . $item['field_id']] = $rule;
				}
			}
			$validate = Validate::rule($rule);
			try {
				$validate->check($data);
				foreach ($arrayField as $value) {
					$data[$value] = implode(',', $data[$value]);
				}
				\app\common\model\User::update($data, ['user_id' => $this->user_id]);
				return doSuccess('success.save');
			} catch (ValidateException $e) {
				return doReturn($e->getError());
			}
		}
		$infomod = explode("\n", $this->settings['infomod']);
		$fields = \app\common\model\Field::whereNotNull('mods')->where('mods', '<>', '')->order('displayorder', 'asc')->where('available', 1)->select()->toArray();
		View::assign('infomod', $infomod);
		View::assign('fields', $fields);
		View::assign('user', $this->user);
		$this->title('资料设置');
		return View::fetch();
	}
	/**
	 * 安全设置
	 * @DateTime 2019-12-21
	 * @Author   BadmintonCode
	 */
	public function password() {
		if ($this->request->isAjax() && $this->request->isPost()) {
			$password = $this->request->post('password', '', 'trim');
			if ($this->user['password'] != salt_password($this->user['salt'], $password)) {
				trace('用户：' . $this->user['email'] . '(' . $this->user['user_id'] . ')修改密码错误', 'notice');
				return doReturn('user.error');
			}
			$data = [];
			if ($this->settings['modifyemail']) {
				//校验邮箱
				$email = $this->request->post('email', '', 'trim,strip_tags');
				if (!$email) {
					return doReturn('email.empty');
				}
				if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
					return doReturn('email.format');
				}
				//判断邮箱是否存在
				if (UserModel::where('user_id', '<>', $this->user['user_id'])->whereEmail($email)->count() > 0) {
					return doReturn('email.exist');
				}
				$data['email'] = $email;
			}
			$newpassword = $this->request->post('newpassword', '', 'trim');
			if ($newpassword) {
				if (strlen($newpassword) < 6) {
					return doReturn('password.short');
				}
				$againpassword = $this->request->post('againpassword', '', 'trim');
				if ($newpassword != $againpassword) {
					return doReturn('password.confirm');
				}
				$data['salt'] = Str::random($length = 16);
				$data['password'] = salt_password($data['salt'], $newpassword);
			}

			UserModel::update($data, ['user_id' => $this->user['user_id']]);
			Session::set('user', UserModel::find($this->user['user_id']));
			return doSuccess('success.modify', ['reload' => true]);
		}
		$this->title('安全设置');
		View::assign('user', $this->user);
		$this->noJs();
		return View::fetch();
	}

	public function avatar() {
		if ($this->request->isAjax() && $this->request->isPost()) {
			$file = request()->file('file');
			try {
				validate(['image' => 'filesize:2048|fileExt:png,bmp,gif,jpg,jpeg,webp'])
					->check(['file' => $file]);
				$rootPath = $this->app->getRootPath() . 'public/storage/';
				// 上传到本地服务器
				$savename = \think\facade\Filesystem::disk('public')->putFile('avatar', $file);
				$src_img = imagecreatefromstring(file_get_contents($rootPath . $savename));
				$new_img = imagecreatetruecolor(256, 256);
				imagecopyresampled($new_img, $src_img, 0, 0, 0, 0, 256, 256, imagesx($src_img), imagesy($src_img));
				$avatarname = explode('.', $savename)[0] . '.png';
				imagepng($new_img, $rootPath . $avatarname);
				if ($avatarname != $savename) {
					@unlink($rootPath . $savename);
				}
				//删除旧的头像
				if (strlen((string) $this->user->avatar) > 32) {
					@unlink($rootPath . $this->user->avatar);
				}
				$this->user->avatar = $avatarname;
				$this->user->save();
				//写入新的头像
				//file_put_contents($);
				return doSuccess(['src' => '/storage/' . $avatarname]);
			} catch (think\exception\ValidateException $e) {
				return doReturn($e->getMessage());
			}

		}
		$this->title('修改头像');
		View::assign('user', $this->user);
		return View::fetch();
	}
}
